import logging; logging.basicConfig(level=logging.DEBUG)
from flask import request, jsonify, current_app
from flask_jwt_extended import create_access_token, create_refresh_token, jwt_required, get_jwt_identity
from backend.api.auth import auth_bp
from backend.api.auth.services import register_user, login_user, refresh_token, reset_password, change_password, logout_user

# 登录接口
@auth_bp.route('/login', methods=['POST'])
def login():
    data = request.get_json(force=True, silent=True)
    if not data:
        logging.error('[login] 未收到有效JSON请求体，返回400')
        return jsonify({'success': False, 'message': '参数错误，未收到有效JSON请求体', 'data': None}), 400
    
    # 获取IP地址和用户代理
    ip_address = request.remote_addr
    user_agent = request.headers.get('User-Agent')
    
    result = login_user(data, ip_address=ip_address, user_agent=user_agent)
    # 如果是数据库不可用，返回 503 以便前端区分
    if result.get('error') == 'db_connect_failed':
        return jsonify(result), 503
    # 仍保持凭证错误返回 200（旧逻辑），可考虑改成 401
    return jsonify(result)

# 注册接口
@auth_bp.route('/register', methods=['POST'])
def register():
    data = request.get_json(force=True, silent=True)
    if not data:
        logging.error('[register] 未收到有效JSON请求体，返回400')
        return jsonify({'success': False, 'message': '参数错误，未收到有效JSON请求体', 'data': None}), 400
    result = register_user(data)
    return jsonify(result)

# 修改密码接口
@auth_bp.route('/change', methods=['POST'])
@jwt_required(optional=True)
def change():
    from flask_jwt_extended import get_jwt_identity, verify_jwt_in_request
    try:
        verify_jwt_in_request()
        logging.warning('[change] JWT 校验通过')
    except Exception as e:
        logging.error('[change] JWT 校验异常: %s', e)
        return jsonify({'success': False, 'message': 'JWT 校验异常', 'data': {'error': str(e)}}), 401
    try:
        data = request.get_json(force=True, silent=True)
    except Exception as e:
        logging.error('[change] 请求体解析异常: %s', e)
        return jsonify({'success': False, 'message': '请求体解析异常', 'data': {'error': str(e)}}), 400
    if not data:
        logging.error('[change] 未收到有效JSON请求体，返回400')
        return jsonify({'success': False, 'message': '参数错误，未收到有效JSON请求体', 'data': None}), 400
    user_id = get_jwt_identity()
    if not user_id:
        logging.error('[change] JWT未携带用户ID，返回401')
        return jsonify({'success': False, 'message': '未认证或Token无效', 'data': None}), 401
    try:
        result = change_password(user_id, data)
        return jsonify(result)
    except Exception as e:
        logging.error('[change] service层异常: %s', e)
        return jsonify({'success': False, 'message': '服务层异常', 'data': {'error': str(e)}}), 500

# 密码重置接口
@auth_bp.route('/reset', methods=['POST'])
def reset():
    data = request.get_json(force=True, silent=True)
    if not data:
        logging.error('[reset] 未收到有效JSON请求体，返回400')
        return jsonify({'success': False, 'message': '参数错误，未收到有效JSON请求体', 'data': None}), 400
    result = reset_password(data)
    return jsonify(result)

# Token刷新接口
@auth_bp.route('/refresh', methods=['POST'])
@jwt_required(refresh=True)
def refresh():
    identity = get_jwt_identity()
    result = refresh_token(identity)
    return jsonify(result)

# Token续期接口（用于活动续期）
@auth_bp.route('/renew', methods=['POST'])
@jwt_required()
def renew_token():
    """用户活动时续期token"""
    try:
        from flask_jwt_extended import get_jwt_identity
        user_id = get_jwt_identity()
        
        # 获取当前用户的角色信息
        from backend.models.user import User
        user = User.query.get(user_id)
        if not user:
            return jsonify({
                'success': False,
                'message': '用户不存在'
            }), 404
            
        # 创建新的token
        roles = [r.name for r in user.roles]
        additional_claims = {"roles": roles}
        new_token = create_access_token(identity=str(user.id), additional_claims=additional_claims)
        
        return jsonify({
            'success': True,
            'access_token': new_token,
            'message': 'Token续期成功'
        })
        
    except Exception as e:
        logging.error('[renew_token] 续期失败: %s', e)
        return jsonify({
            'success': False,
            'message': f'Token续期失败: {str(e)}'
        }), 500

# 登出接口
@auth_bp.route('/logout', methods=['POST'])
@jwt_required(refresh=True)
def logout():
    from flask_jwt_extended import get_jwt_identity
    user_id = get_jwt_identity()
    
    # 获取IP地址
    ip_address = request.remote_addr
    
    result = logout_user(user_id, ip_address=ip_address)
    return jsonify(result)

# 认证状态检查接口
@auth_bp.route('/check', methods=['GET'])
@jwt_required(optional=True)
def check_auth():
    """检查用户认证状态"""
    try:
        from flask_jwt_extended import get_jwt_identity, verify_jwt_in_request
        # 尝试验证JWT
        verify_jwt_in_request(optional=True)
        user_id = get_jwt_identity()
        
        if user_id:
            # 用户已认证
            return jsonify({
                'success': True,
                'authenticated': True,
                'user_id': user_id,
                'message': '用户已认证'
            })
        else:
            # 用户未认证
            return jsonify({
                'success': True,
                'authenticated': False,
                'message': '用户未认证'
            })
    except Exception as e:
        logging.error('[check_auth] JWT检查异常: %s', e)
        return jsonify({
            'success': True,
            'authenticated': False,
            'message': 'Token无效或已过期'
        })
